/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-14
 * Time: 11:20
 */
class MyBlockingQueue{
    private int[] elem;
    private  volatile int size;
    private  volatile int head;
    private  volatile int tail;

    public MyBlockingQueue(int capacity){
        elem=new int[capacity];
    }
    public void put(int value) throws InterruptedException {
        synchronized (this){
            if(size==elem.length){
               this.wait();
            }
            elem[tail]=value;
            tail++;
            size++;
            if(tail==elem.length){
                tail=0;
            }
            this.notify();
        }


    }
    public int take() throws InterruptedException {
        int value=0;
        synchronized (this) {

            if (size == 0) {
                this.wait();
            }
                 value = elem[head];
                head++;
                size--;
                if (head >= elem.length) {
                    head = 0;
                }
                this.notify();


            }

            return value;
        }

}
public class Demo7 {
    public static void     main(String[] args) throws InterruptedException {
        MyBlockingQueue myBlockingQueue=new MyBlockingQueue(10);
     Thread t1=new Thread(()->{
         for (int i = 0; i < 1000; i++) {
             try {
                 myBlockingQueue.put(i);
                 System.out.println("t1 生产:"+i);

             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     });
     Thread t2=new Thread(()->{
         while(true){
             int value= 0;
             try {
                 value = myBlockingQueue.take();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
             System.out.println("t2消费:"+value);
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     });
     t1.start();
     t2.start();

    }
}
